package com.example.origin.redis.controller;


import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

public class Cache<V> {

    private RedisTemplate<String, V> redisTemplate;

    private ThreadPoolExecutor threadPoolExecutor;

    public Cache(RedisTemplate<String, V> redisTemplate,ThreadPoolExecutor threadPoolExecutor) {
        this.redisTemplate = redisTemplate;
        this.threadPoolExecutor = threadPoolExecutor;
    }

    public V get(String key, Supplier<V> supplier) {
        //取数逻辑
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null) {
            synchronized (Cache.class) {
                o = redisTemplate.opsForValue().get(key);
                if (o == null) {
                    V v = supplier.get();
                    update(key, v);
                }
            }
        }
        int activeCount = threadPoolExecutor.getActiveCount();
        BlockingQueue<Runnable> queue = threadPoolExecutor.getQueue();

        if (activeCount == 0 || queue.isEmpty()) {
            synchronized (Cache.class) {
                if (activeCount == 0 || queue.isEmpty()) {
                    threadPoolExecutor.execute(() -> {
                        V v = supplier.get();
                        update(key, v);
                    });
                }
            }
        }

        return (V) o;

    }

    private void update(String key, V value) {
        //更新数据的逻辑
        redisTemplate.opsForValue().set(key, value, 10, TimeUnit.SECONDS);
    }
}

